//
//  AppDelegate.m
//  MovieDate
//
//  Created by 杨运涛 on 16/3/11.
//  Copyright © 2016年 MovieDate. All rights reserved.
//

#import "AppDelegate.h"
#import "UMessage.h"
#import "MobClick.h"

#import "APIKey.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>

#import "Lotuseed.h"

#define UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define _IPHONE80_ 80000

@interface AppDelegate () <MAMapViewDelegate, CLLocationManagerDelegate, AMapSearchDelegate>
{
    MAMapView *pMapView;
    AMapSearchAPI *_search;
}
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:240/255.0f green:240/255.0f blue:240/255.0f alpha:1]];
    
    //莲子数据
    [Lotuseed setCrashReportEnabled:YES]; //是否提交程序异常报告
    [Lotuseed startWithAppKey:@"m0W7U5vw8WdIcqUbGjco"]; //必须添加的接口调用 //其他Lotuseed API调用请放在startWithAppKey()后!!!
    [Lotuseed updateOnlineConfig]; //更新在线参数配置
    
    
    // Override point for customization after application launch.
    [self configureAPIKey];
    
    [UMessage startWithAppkey:UMENG_APP_KEY launchOptions:launchOptions];
    
    [MobClick setLogEnabled:YES];  // 打开友盟sdk调试，注意Release发布时需要注释掉此行,减少io消耗
    [MobClick setAppVersion:XcodeAppVersion]; //参数为NSString * 类型,自定义app版本信息，如果不设置，默认从CFBundleVersion里取
    [MobClick startWithAppkey:UMENG_APP_KEY reportPolicy:(ReportPolicy)BATCH channelId:nil];
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
    if(UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
    {
        //register remoteNotification types
        UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"action1_identifier";
        action1.title=@"Accept";
        action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];  //第二按钮
        action2.identifier = @"action2_identifier";
        action2.title=@"Reject";
        action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序，在后台处理
        action2.authenticationRequired = YES;//需要解锁才能处理，如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略；
        action2.destructive = YES;
        
        UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
        categorys.identifier = @"category1";//这组动作的唯一标示
        [categorys setActions:@[action1,action2] forContext:(UIUserNotificationActionContextDefault)];
        
        UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert
                                                                                     categories:[NSSet setWithObject:categorys]];
        [UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];
        
    } else {
        //register remoteNotification types
        [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
        |UIRemoteNotificationTypeSound
        |UIRemoteNotificationTypeAlert];
    }
#else
    
    //register remoteNotification types
    [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
    |UIRemoteNotificationTypeSound
    |UIRemoteNotificationTypeAlert];
    
#endif
    
    return YES;
}

//推送功能开启或关闭
- (void)selCloseNoti {
    if (![[NSUserDefaults standardUserDefaults] boolForKey:MACROS_KEY_DISAGREE_UMPUSH]) {
        [UMessage addTag:[[NSUserDefaults standardUserDefaults] objectForKey:MACROS_KEY_DEVICE_TOKEN] response:^(id responseObject, NSInteger remain, NSError *error) {}];
    } else {
        [UMessage removeTag:[[NSUserDefaults standardUserDefaults] objectForKey:MACROS_KEY_DEVICE_TOKEN] response:^(id responseObject, NSInteger remain, NSError *error) {}];
    }
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *strDeviceToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
    [[NSUserDefaults standardUserDefaults] setValue:strDeviceToken forKey:MACROS_KEY_DEVICE_TOKEN];
    NSLog(@"deviceToken:%@", strDeviceToken);
    
    [UMessage registerDeviceToken:deviceToken];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


#pragma mark - 友盟推送

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    //如果注册不成功，打印错误信息，可以在网上找到对应的解决方案
    //如果注册成功，可以删掉这个方法
    NSLog(@"application:didFailToRegisterForRemoteNotificationsWithError: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    //关闭友盟自带的弹出框
    //  [UMessage setAutoAlert:NO];
//    [UMessage didReceiveRemoteNotification:userInfo];
}


#pragma mark - 地图定位

- (void)configureAPIKey
{
    if ([APIKey length] == 0)
    {
        NSString *reason = [NSString stringWithFormat:@"apiKey为空，请检查key是否正确设置。"];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:reason delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
        [alert show];
    }
    
    [MAMapServices sharedServices].apiKey = (NSString *)APIKey;
    
    pMapView = [[MAMapView alloc] init];
    [pMapView setFrame:CGRectMake(0, 0, 0, 0)];
    pMapView.delegate = self;
    pMapView.userTrackingMode = MAUserTrackingModeFollow;
}

#pragma mark - 高德地图代理 MAMapViewDelegate

- (void)mapView:(MAMapView *)mapView didFailToLocateUserWithError:(NSError *)error {
}

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    NSString *strLatitude = [NSString stringWithFormat:@"%f", userLocation.location.coordinate.latitude];
    NSString *strLongitude = [NSString stringWithFormat:@"%f", userLocation.location.coordinate.longitude];
    
    [User defaultUser].pStrLatitude = strLatitude;
    [User defaultUser].pStrLongitude = strLongitude;

    if ([strLatitude intValue] - 1 < 0 && [strLongitude intValue] - 1 < 0) {
    } else {
        //逆编码地址
        //初始化检索对象
        [AMapSearchServices sharedServices].apiKey = (NSString *)APIKey;
        _search = [[AMapSearchAPI alloc] init];
        _search.delegate = self;
        
        //构造AMapReGeocodeSearchRequest对象，location为必选项，radius为可选项
        AMapReGeocodeSearchRequest *regeoRequest = [[AMapReGeocodeSearchRequest alloc] init];
        regeoRequest.location = [AMapGeoPoint locationWithLatitude:[strLatitude floatValue] longitude:[strLongitude floatValue]];
        regeoRequest.requireExtension = YES;
        //发起逆地理编码
        [_search AMapReGoecodeSearch: regeoRequest];
        
        pMapView.showsUserLocation = NO;
        [pMapView removeAnnotations:pMapView.annotations];
        [pMapView removeOverlays:pMapView.overlays];
        pMapView.delegate = nil;
        [pMapView setCompassImage:nil];
    }
}

//实现逆地理编码的回调函数
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    if(response.regeocode != nil) {
        [User defaultUser].pStrLocationAddress = [NSString stringWithFormat:@"%@%@%@", response.regeocode.addressComponent.province, response.regeocode.addressComponent.city, response.regeocode.addressComponent.district];
    }
    NSLog(@"%@", [User defaultUser].pStrLocationAddress);
}

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error {
    NSLog(@"%s: searchRequest = %@, errInfo= %@", __func__, [request class], error);
}

@end
